from datetime import datetime
from json import dump
from os.path import join
from re import search, sub
from django.db.models import Q
from django.http import JsonResponse
from learningPlanet.models import Blog
from log.models import RequestLogTable
from myTool.tools import timestamp_to_date, topStat, statisticData


# 返回可视化的代码
def returnPicture(request):
    if request.method == 'POST':
        whichOne = request.POST.get('whichOne')  # 1代表月数据 2代表年数据
        with open(join('templates',f'demo{whichOne}.html'), 'r', encoding='utf8') as f:
            content = f.read().replace(
                '<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>', '')
            div = search(r'<div.*div>', content).group()
            return JsonResponse({'div': div})  # ,'script':script
    return JsonResponse({'div': '数据请求失败!'})


# 绘制数据显示图标并将其写入文件
def drawPictureAndWriteToFile():
    for i in range(1, 3):
        statisticData(RequestLogTable, i)  # 绘图1和图2
        with open(join('templates',f'demo{i}.html'), 'r', encoding='utf8') as f:
            content = f.read().replace(
                '<script type="text/javascript" src="https://assets.pyecharts.org/assets/echarts.min.js"></script>', '')
            script = sub(
                r'(<div.*div>)|</script>|<script>|<!DOCTYPE html>|<html>|<head>|<meta charset="UTF-8">|<title>Awesome-pyecharts</title>|</head>|<body>|</body>|</html>',
                '', content)
        with open(join('static', 'js', f'demo{i}.js'), 'w+', encoding='utf8') as f:
            f.write(script)


def doTopStat():
    # 热门推荐 日热门/周热门/月热门 前5条数据
    nowTime = datetime.now()
    second, minute, hour, day, month, year = nowTime.second, nowTime.minute, nowTime.hour, nowTime.day, nowTime.month, nowTime.year
    # 当年的所有学习星球的访问记录
    blogObjs = RequestLogTable.objects.filter(
        Q(requestTime__year=year) & Q(requestPath__regex='/learningPlanet/[0-9]*$'))

    # 月热门
    topMonth = blogObjs.filter(requestTime__month=month)
    # 日热门
    topDay = topMonth.filter(requestTime__day=day)
    # 周热门
    startTime = timestamp_to_date(nowTime.timestamp() - 7 * 24 * 60 * 60)  # 七天前
    topWeek = blogObjs.filter(Q(requestTime__gte=startTime) & Q(requestTime__lte=nowTime))
    resTopDay = topStat(topDay, Blog)
    resTopMonth = topStat(topMonth, Blog)
    resTopWeek = topStat(topWeek, Blog)
    conDic = {'day': resTopDay, 'month': resTopMonth, 'week': resTopWeek}
    with open(join('data', 'data.json'), 'w', encoding='utf8') as f:
        dump(conDic, f)


# 定时任务
from apscheduler.scheduler import Scheduler

# 实例化
sched = Scheduler()


# 每一小时执行一次
@sched.interval_schedule(seconds=3600)  # 3600
def sched_test():
    # 刷新排行榜
    doTopStat()
    # 刷新后台的统计数据
    drawPictureAndWriteToFile()
sched.start()
